package com.ww.springboot.drools.service.impl;

import com.ww.springboot.drools.bean.Person;
import com.ww.springboot.drools.service.TestService;
import com.ww.springboot.drools.util.ThreadLocalUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.drools.core.event.DebugRuleRuntimeEventListener;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;
import org.kie.internal.utils.KieHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述：
 *
 * @author wanwei
 * @since 2021-11-24 09:25
 */
@Service
public class TestServiceImpl implements TestService {

    //@Resource
    //private KieSession kieSession;

    private static ConcurrentHashMap<String, KieBase> concurrentHashMap = new ConcurrentHashMap<>();

    @Override
    public void test() {
//        System.out.println("-------test start-----");
//
//        Person person = new Person();
//        person.setName("张三");
//        System.out.println("-------java start " + person.getName() + "-----------");
//        kieSession.insert(person);
//        int ruleFiredCount = kieSession.fireAllRules();
//        System.out.println(ruleFiredCount);
//        System.out.println("-------java end " + person.getName() + "-----------");
//        System.out.println("-------test end-----");
    }

    @Override
    public void initRule() {
        String ruleStr = "package com.drools.rules\n" +
                "\n" +
                "rule \"springboot原始整合方式2\"\n" +
                "       when\n" +
                "       then\n" +
                "        System.out.println(\"springboot原始整合方式2\");\n" +
                "        end";
        String ruleStr2 = "package com.drools.rules\n" +
                "\n" +
                "import com.ww.springboot.drools.bean.Person\n" +
                "\n" +
                "rule \"规则测试person值2\"\n" +
                "    when\n" +
                "        $p:Person(name == \"张三\")\n" +
                "    then\n" +
                "        $p.setName($p.getName()+\"xxx2\");\n" +
                "        System.out.println($p);\n" +
                "        System.out.println(\"规则测试person值\");\n" +
                "     end";
        String ruleStr3 = "package com.drools.rules\n" +
                "\n" +
                "import com.ww.springboot.drools.bean.Person\n" +
                "\n" +
                "//str 是否匹配正则表达式 对象为表达式\n" +
                "rule \"demo1\"\n" +
                "    when\n" +
                "        Person(name str[length] 1)\n" +
                "        Person(name str[startsWith] \"张\")\n" +
                "    then\n" +
                "        System.out.println(\"str语法测试\");\n" +
                "     end";
//        KieHelper helper = new KieHelper();
//        helper.addContent(ruleStr, ResourceType.DRL);
//        helper.addContent(ruleStr2, ResourceType.DRL);
//        helper.addContent(ruleStr3, ResourceType.DRL);
//        KieSession kieSession = helper.build().newKieSession();
        KieBase kieBase = buildSession(ruleStr2);
        concurrentHashMap.put("kieBase", kieBase);
    }


    private KieBase buildSession(String rule) {

        KieServices kieServices = KieServices.Factory.get();
        KieFileSystem kfs = kieServices.newKieFileSystem();
        try {
            kfs.write("src/main/resources/com/drools/rules/" + System.currentTimeMillis() + ".drl", rule.getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        KieBuilder kieBuilder = kieServices.newKieBuilder(kfs).buildAll();
        if (!kieBuilder.getResults().getMessages(Message.Level.ERROR).isEmpty()) {
            throw new RuntimeException("Drools初始化失败,请检查Drools语句");
        }
        KieContainer kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());
        KieBase kBase = kieContainer.getKieBase();
        return kBase;
    }

    @Override
    public void test3(Person person) {
        KieBase kieBase = concurrentHashMap.get("kieBase");
        KieSession kieSession = kieBase.newKieSession();
        kieSession.addEventListener(new DebugRuleRuntimeEventListener());
        try {
            System.out.println("-------test start-----");
            System.out.println("-------java start " + person.getName() + "-----------");
            kieSession.insert(person);
            System.out.println(kieSession.getObjects().size());
            int ruleFiredCount = kieSession.fireAllRules();
            System.out.println("匹配规则:" + ruleFiredCount);
            System.out.println(kieSession.getObjects().size());
            System.out.println("-------java end " + person.getName() + "-----------");
            System.out.println("-------test end-----");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            kieSession.dispose();
        }
    }
}
